package net.lovesrc.allin.biz.dida;

import com.alibaba.fastjson.JSONObject;
import freemarker.template.Configuration;
import freemarker.template.Template;
import net.lovesrc.allin.Message;
import net.lovesrc.allin.biz.NotificationService;
import net.lovesrc.allin.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.StringWriter;

@RestController
@RequestMapping("/dida")
public class DidaController extends BaseController {

    @Autowired
    private Configuration configuration;

    @Autowired
    private RideService rideService;

    @GetMapping("/rides")
    public Message rides() {
        return Message.success(rideService.getAll());
    }

    @GetMapping("/ride/{id}")
    public Message ride(@PathVariable Long id) {
        return Message.success(rideService.getById(id));
    }

    @PostMapping("/ride/change-enable-status")
    public Message rideChangeEnableStatus(@RequestBody JSONObject params) {
        rideService.changeEnableStatus(params.getLong("id"), params.getBooleanValue("enabled"));
        return Message.success();
    }

    @GetMapping("/ride/{id}/query")
    public Message rideQueryListing(@PathVariable Long id) {
        return Message.success(rideService.query(id));
    }

    @GetMapping("/ride/{id}/forecast")
    public Message rideForecastListing(@PathVariable Long id) {
        return Message.success(rideService.forecast(id));
    }

    @PostMapping("/ride/add")
    public Message rideAdd(@RequestBody JSONObject params) {
        rideService.save(params.toJavaObject(Ride.class));
        return Message.success();
    }

    @PostMapping("/ride/email/{rideId}")
    public Object email(@PathVariable Long rideId) throws Exception {
        JSONObject orderDetail = rideService.getAndSaveRideOrderDetail(rideId);
        Listing listing = orderDetail.toJavaObject(Listing.class);
        StringWriter stringWriter = new StringWriter();
        Template template = configuration.getTemplate("dida/listing-qiang.ftl");
        template.process(listing, stringWriter);
        String html = stringWriter.toString();
        stringWriter.close();
        String title;
        title = String.format("Qiang, %s to %s", listing.getFromPoi().getShortAddress(), listing.getToPoi().getShortAddress());
        notificationService.email(NotificationService.LZQ_EMAIL, title, html);
        return Message.success();
    }

}
